#                ,            
#   _  _/_ __    __   _   _  
#  /_)_(__/ (__(_/ (_(_/_/_)_
#                   .-/      
#                  (_/       
#
#  http://stringswiki.com
#  Understanding the simplicity
#  Copyright 2009, Asbjorn Enge. All rights reserved.
#
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program; if not, write to the Free Software
#  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
#  MA  02111-1307  USA
#
#  (C) 2009
"""

	strings.py - Strings main application


"""
__author__  = 'Asbjorn Enge <asbjorn@hanafjedle.net>'

from request import Request, tune_controller
from router import Router
from thread import get_request, RegisterRequest

from paste.evalexception import EvalException

from setuptools import find_packages

def start(conf):
	import sys, os, pdb

	app = Router()
	app_modules = {}

	## Scan products directory for apps, add and tune them
	#
	for prod in conf['products']:
		# TODO: Add this to path in bin/strings with recipe ?
		sys.path.append(os.curdir + '/' + prod)
		for module_name in find_packages(prod,exclude=['*.*']):
			print "--- Setting up package - %s ---" % module_name
			module = __import__(module_name)
			tunes = hasattr(module, "tunes") and module.tunes or []
			controller = hasattr(module, "controller") and module.controller or tune_controller
			for tune in tunes:
				if isinstance(tune, type):
					controller_class = controller(tune)
					route = hasattr(tune, 'route') and tune.route or '/%s' % tune.__name__
					routes = hasattr(tune, 'routes') and tune.routes or {}
					app.add_route(route, controller=controller_class)
					for r in routes.keys():
						app.add_route(r, controller=controller_class, action=routes[r])
			if hasattr(module, "tune"):
				app = module.tune(app)
				print "Strings tuned."
			print "-- Complete --"

	app = RegisterRequest(app)
	app = EvalException(app)
	
	from paste import httpserver
	httpserver.serve(app, host='localhost', port=conf['port'])
